// ActionScript file
package {
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;
    import flash.net.URLRequestHeader;
    import flash.net.URLRequestMethod;
    import flash.net.URLVariables;
    import flash.utils.ByteArray;
    
    import ru.vkontakte.MD5;
    
    public class Reactor {
        private var _cookies:Object = null;
        private var _email:String = null;
        private var _pwd:String = null;
        
        public function Reactor() {
            
        }
        
        public function login(email:String, pwd:String):void {
            _cookies = null;
            _email = email;
            _pwd = pwd;
            var params:Object = {
                'op': 'a_login_attempt', 
                'email': email, 
                'pass': pwd, 
                'expire': 0
            };
            makeRequest("login.php", params, onLogin);
        }
        
        private function onLogin(data:String):void {
            if (data.substr(0, 4) == "good") {
                var id:int = Number(data.substr(4));
                _cookies = {
                    'remixmid' : id,
                    'remixemail' : _email.split("@").join("%40"),
                    'remixpass' : MD5.encrypt(_pwd)
                };
                makeRequest("newsfeed.php", null, onNews);
            }    
        }
        
        private function onNews(data:String):void {
            trace("news: " + data);
        }
        
        private function makeRequest(method:String, params:Object, cb:Function):void {
            var req:URLRequest = new URLRequest("http://vkontakte.ru/" + method);
            if (params) {
                req.data = new URLVariables();
                for (var k:String in params)
                    req.data[k] = params[k];
            }
            if (_cookies) {
                var cookies:Array = []
                for (var name:String in _cookies)
                    cookies.push(name + "=" + _cookies[name]) 
                req.requestHeaders.push(new URLRequestHeader('Cookie', cookies.join("; "))); 
            }
            req.method = URLRequestMethod.POST;
            var loader:URLLoader = new URLLoader();
            loader.dataFormat = URLLoaderDataFormat.BINARY;
            loader.addEventListener(Event.COMPLETE, function (e:Event):void {
                var ba:ByteArray = loader.data;
                ba.position = 0;
                const data:String = ba.readMultiByte(ba.length, "windows-1251");
                if (cb != null)
                    cb(data);
            });
            loader.load(req);
        }
    }
}